package app.cloudstringers;

import java.util.Timer;
import java.util.TimerTask;

import utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.mobeta.android.dslv.DragSortListView;

import controller.CheckHBAsync;
import controller.PriorityListAsync;
import define.Constants;
import define.DefaultValue;
import define.Key;
import define.SharedPreference;
import define.Status;

public class PriorityList extends Activity {
	/**
	 * String section
	 */
	public static boolean IS_CHANGE_PRIORITY_IN_CONNECTED_STATE = false;
	public static boolean IS_CHANGE_PRIORITY_IN_DISCONNECTED_STATE = false;
	public static boolean IS_CHANGE_STATE = false;
	public static boolean IS_FIRST_TIME_TO_CHECK_HB = true;
	public static boolean IS_FIRST_TIME_TO_PRIORITY_LIST = true;

	private static final String TAG = PriorityList.class.getSimpleName();

	private static String ID = null, SELL = null;

	/**
	 * View section
	 */
	private AlertDialog.Builder mDialogLogin, mDialogLogout;
	private AlertDialog.Builder mDialogExit;
	public static ImageButton mIbtnChangePriority;
	public static ImageButton mIbtnRefresh;
	public static ImageButton mIbtnSubmit;
	public static DragSortListView DragSortListViewPriorityList;
	public static ProgressDialog mPdWaiting;
	public static TextView mTvCardStatus;

	/**
	 * Others section
	 */
	private SharedPreferences.Editor mSpEditor;
	private SharedPreferences mSpSettings;
	private Handler mHandler = new Handler();

	private Timer mTimerRefreshHB = null;
	// Timer task
	private TimerTask mTtRefreshHB = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_priority_list);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		Constants.utils = new Utils(this);

		// Initial dialogs & variables
		initialDialogs();
		initialVariables();
	}

	/**
	 * On clicked method
	 */
	public void onClickPriorityList(View v) {
		switch (v.getId()) {
		case R.id.ibtn_change_priority_in_priority_list:
			Log.i(TAG, "BEGIN CHANGE PRIORITY");
			/**
			 * If Change Priority button was pressed And from Disconnected to
			 * Connected state Need check something before directly to Change
			 * Priority feature in Connected state
			 */
			if (Integer.valueOf(PriorityListAsync.CURRENT_STATUS_HB) == Status.STATUS_HB_CONNECTED) {
				Log.i(TAG, "Connected state");

				IS_CHANGE_PRIORITY_IN_CONNECTED_STATE = true;

				// Clear the list
				if (PriorityListAsync.mLlItems != null
						& !PriorityListAsync.mLlItems.isEmpty()) {
					PriorityListAsync.mLlItems.clear();
				}

				// send status=stop
				new PriorityListAsync(this)
						.execute(ID, Status.STATUS_STOP + "");
			} else {
				Log.i(TAG, "DisConnected state");

				IS_CHANGE_PRIORITY_IN_DISCONNECTED_STATE = true;

				// Hide Change Priority button, Show Submit button
				mIbtnChangePriority.setVisibility(View.GONE);
				mIbtnSubmit.setVisibility(View.VISIBLE);

				// Clear the list
				if (PriorityListAsync.mLlItems != null
						& !PriorityListAsync.mLlItems.isEmpty()) {
					PriorityListAsync.mLlItems.clear();
				}

				// send user_id
				new PriorityListAsync(this).execute(ID,
						Status.STATUS_GET_LIST_OF_FILES + "");
			}

			CheckHBAsync.avoidChangeFileOrder();
			CheckHBAsync.avoidShowRefreshButton();
			break;
		case R.id.ibtn_home_in_priority_list:
			Intent intent = new Intent(PriorityList.this, Home.class);
			finish();
			startActivity(intent);

			break;
		case R.id.ibtn_logout_in_priority_list:
			mDialogLogout.show();
			break;
		case R.id.ibtn_refresh_in_priority_list:
			/**
			 * Reset all things before go to Priority List tab again
			 */
			define.PriorityList.IS_TIME_OUT = false;

			// Clear the list
			if (PriorityListAsync.mLlItems != null
					& !PriorityListAsync.mLlItems.isEmpty()) {
				PriorityListAsync.mLlItems.clear();
			}

			new PriorityListAsync(this).execute(ID,
					Status.STATUS_GET_LIST_OF_FILES + "");

			break;
		case R.id.ibtn_submit_in_priority_list:
			if (Integer.valueOf(PriorityListAsync.CURRENT_STATUS_HB) == Status.STATUS_HB_CONNECTED) {
				if (mPdWaiting == null) {
					mPdWaiting = ProgressDialog.show(this,
							getString(R.string.title_loading),
							getString(R.string.content_loading));
				}

				PriorityListAsync.IS_SUBMIT = true;

				// Not Clear the current list before submitting to the server
				// send status=submit
				new PriorityListAsync(this).execute(ID, Status.STATUS_SUBMIT
						+ "");
			} else {
				// Show Change Priority button, Hide Submit button
				mIbtnChangePriority.setVisibility(View.VISIBLE);
				mIbtnSubmit.setVisibility(View.GONE);

				// Can not move files
				CheckHBAsync.avoidChangeFileOrder();
				CheckHBAsync.avoidShowRefreshButton();

				// Notify change
				PriorityListAsync.refreshPriorityListItemAdapter
						.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		/**
		 * Reset all things before go to Priority List tab again
		 */
		// utils.PriorityList.IS_PAUSED_RESUMED_PRIORITIED = false;
		if (define.PriorityList.timeoutTimer != null) {
			define.PriorityList.timeoutTimer.onFinish();
			define.PriorityList.timeoutTimer = null;
		}

		if (mTimerRefreshHB != null) {
			mTimerRefreshHB = null;
		}
		if (mTtRefreshHB != null) {
			mTtRefreshHB.cancel();
			mTtRefreshHB = null;
		}

		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			mDialogExit.show();
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onResume() {
		super.onResume();

		if (Constants.utils.isNetworkOnline()) {
			// Set the first time go to Check HB class
			// to refresh get new list item
			// as get new state also
			if (!IS_FIRST_TIME_TO_CHECK_HB) {
				IS_FIRST_TIME_TO_CHECK_HB = true;
			}

			// Get data from shared preference
			mSpSettings = getSharedPreferences(SharedPreference.PREFS,
					Context.MODE_PRIVATE);
			mSpEditor = mSpSettings.edit();

			// Get ID
			ID = mSpSettings.getString(SharedPreference.PREFS_KEY_GLOBAL_ID,
					DefaultValue.DEFAULT_GLOBAL_ID + "");
			SELL = mSpSettings.getString(SharedPreference.PREFS_KEY_SELL,
					Key.KEY_CANNOT_BUY_CANNOT_SELL + "");

			// This always happened when was disconnected
			// If the connection dialog has shown, dismiss it before show new
			// dialog
			Utils.hideConnectionDialog();

			/**
			 * If the user account is General User: 0 or 2, not allow work with
			 * this tab
			 */
//			if (Integer.valueOf(SELL) != Key.KEY_CANNOT_BUY_CANNOT_SELL
//					& Integer.valueOf(SELL) != Key.KEY_CAN_BUY_CANNOT_SELL) {
			if (1==1) {
				/**
				 * Create Timer 30s to always check new HB
				 */
				if (mTimerRefreshHB != null | mTtRefreshHB != null) {
					mTimerRefreshHB = null;
					mTtRefreshHB.cancel();
					mTtRefreshHB = null;
				}

				mTimerRefreshHB = new Timer();
				mTtRefreshHB = new TimerTask() {
					@Override
					public void run() {
						mHandler.post(new Runnable() {

							@Override
							public void run() {
								// Call Checking HB process
								// Send
								// - Flag
								// - ID
								// - STATUS
								/**
								 * NOT RUN WHEN IS_STOP=true or
								 * IS_SUBMITTED=true
								 */
								if (!PriorityListAsync.IS_STOP
										& !define.PriorityList.IS_SUBMITTED) {
									Log.i(TAG,
											"BEGIN REFRESH TO CHECK HB STATUS.");

									new CheckHBAsync(PriorityList.this)
											.execute(ID, Status.STATUS_HB + "");
								}
							}
						});
					}
				};
				mTimerRefreshHB.schedule(mTtRefreshHB, 0,
						define.Timer.TIMER_REFRESH_IN_PRIORITY_LIST_TAB);
			} else {
				// Hide Change Priority button, Refresh button, Submit button
				// Hide Card was disconnected also
				mIbtnChangePriority.setVisibility(View.INVISIBLE);
				mIbtnRefresh.setVisibility(View.INVISIBLE);
				mIbtnSubmit.setVisibility(View.INVISIBLE);
				mTvCardStatus.setVisibility(View.INVISIBLE);
			}
		} else {
			Utils.hideConnectionDialog();
			Utils.showConnectionDialog();
		}
	}

	/**
	 * Initial methods
	 */
	private void initialDialogs() {
		mDialogLogin = new AlertDialog.Builder(this);
		mDialogLogin.setTitle(getString(R.string.title_login));
		mDialogLogin.setCancelable(false);
		mDialogLogin.setMessage(getString(R.string.content_login));
		mDialogLogin.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						// new intent to Status tab
						Intent intent = new Intent(PriorityList.this,
								StatusTab.class);
						finish();
						startActivity(intent);
					}
				});

		mDialogLogout = new AlertDialog.Builder(this);
		mDialogLogout.setTitle(getString(R.string.title_logout));
		mDialogLogout.setCancelable(false);
		mDialogLogout.setMessage(getString(R.string.content_logout));
		mDialogLogout.setPositiveButton(R.string.yes,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						// set data for shared preferences
						mSpEditor.putString(
								SharedPreference.PREFS_KEY_USER_NAME, "user");
						mSpEditor.putString(
								SharedPreference.PREFS_KEY_GLOBAL_ID,
								DefaultValue.DEFAULT_GLOBAL_ID + "");
						mSpEditor.commit();

						// new intent to login page
						Intent intent = new Intent(PriorityList.this,
								Login.class);
						finish();
						startActivity(intent);
					}
				});
		mDialogLogout.setNegativeButton(R.string.no,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});

		mDialogExit = new AlertDialog.Builder(PriorityList.this);
		mDialogExit.setTitle(R.string.title_exit);
		mDialogExit.setIcon(R.drawable.ic_info_normal);
		mDialogExit.setCancelable(false);
		mDialogExit.setMessage(R.string.content_exit);
		mDialogExit.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		mDialogExit.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
					}
				});
	}

	private void initialVariables() {
		mIbtnChangePriority = (ImageButton) findViewById(R.id.ibtn_change_priority_in_priority_list);
		mIbtnRefresh = (ImageButton) findViewById(R.id.ibtn_refresh_in_priority_list);
		mIbtnSubmit = (ImageButton) findViewById(R.id.ibtn_submit_in_priority_list);
		DragSortListViewPriorityList = (DragSortListView) findViewById(R.id.lv_in_priority_list);
		mTvCardStatus = (TextView) findViewById(R.id.tv_card_status_in_priority_list);
	}

	/**
	 * Basic methods
	 */
}
